// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import VueRouter from 'vue-router'
import router from './router'
import lodash from 'lodash'
import Vant, { Lazyload, Toast, Dialog, Row, Col, RadioGroup, Radio } from 'vant'
import axios from 'axios'
import './common/index.css'
import index from './directive/index'
import conf from './conf/index'
import date from './filter/date'
import qnImg from './filter/qn-img'
import Cookies from 'js-cookie'

Vue.filter('date', date)
Vue.filter('qnImg', qnImg)

Vue.use(VueRouter).use(Vant).use(Lazyload, {
  lazyComponent: true
}).use(Row).use(Col).use(Radio).use(RadioGroup)
Vue.prototype.$date = date
Vue.prototype.$lodash = lodash
Vue.prototype.$toast = Toast
Vue.prototype.$dialog = Dialog
Vue.prototype.$axios = axios.create({
  baseURL: conf.host.host.ip + ':' + conf.host.host.port,
  timeout: conf.host.host.timeout,
  headers: { 'Authorization': Cookies.get('access_token') }
})

// 返回数据格式化
Vue.prototype.$axios.interceptors.response.use(res => {
  if (res.status === 200) {
    // 裁剪数据
    return res
  }
}, (err) => {
  if (err.response.status === 400) {
    Vue.prototype.$toast(err.response.data.message)
    throw (err)
  }
  if (err.response.status === 500) {
    Vue.prototype.$toast('服务器出了点问题')
  }
})
Vue.config.productionTip = false

// 路由请求开始时调用
router.beforeEach(function (to, from, next) {
  if (Cookies.get('access_token')) {
    next()
  } else {
    if (to.query.token) {
      Vue.prototype.$axios.get('/wechat/' + to.query.token).then(data => {
        console.log('access_token', data)
        if (data && data.data.token) {
          Cookies.set('access_token', data.data.token, { expires: 7 })
          localStorage.user = JSON.stringify(data.data.session)
          Vue.prototype.$axios = axios.create({
            baseURL: conf.host.host.ip + ':' + conf.host.host.port,
            timeout: conf.host.host.timeout,
            headers: { 'Authorization': Cookies.get('access_token') }
          })
        } else {
          window.location.href = conf.host.host.ip + '/wechat'
        }
      })
      next()
    } else {
      if (!localStorage.user && to.query.redirect_id) {
        Vue.prototype.$axios.post('/wechat/redirect', {
          id: to.query.redirect_id
        }).then(data => {
          window.location.href = conf.host.host.ip + '/wechat'
        })
      } else {
        window.location.href = conf.host.host.ip + '/wechat'
      }
    }
  }
})

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  directives: index,
  components: { App },
  template: '<App/>'
})
